package com.example.api.client.fallback;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.api.client.OrderClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;

/**
 * 订单服务降级处理
 */
public class OrderFallback implements FallbackFactory<OrderClient> {
    private static final Logger log = LoggerFactory.getLogger(OrderFallback.class);

    @Override
    public OrderClient create(Throwable cause) {
        log.error("订单服务调用失败:{}", cause.getMessage());

        if (cause instanceof BlockException) {
            // 如果抛出的异常是Sentinel的阻塞异常，则返回一个降级处理的实例
            return new OrderClient() {
                @Override
                public String create(String userId, String commodityCode, int orderCount) {
                    return "Sentinel 限流或熔断了服务调用，返回的降级响应：" + userId;
                }
            };
        } else {
            // 其他异常则返回一个简单的错误信息
            return new OrderClient() {
                @Override
                public String create(String userId, String commodityCode, int orderCount) {
                    return "FeignClient 服务调用出现异常，返回的降级响应：" + userId;
                }
            };
        }
    }
}
